package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Controller
public class UserController {
    private Logger logger = Logger.getLogger(UserController.class.getName());

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/login.html")
    public String login(){
        return "login";
    }

    @Autowired
    private UserService userService;

    @RequestMapping("/doLogin.html")
    public String doLogin(@RequestParam String userCode,
                          @RequestParam String userPassword,
                          HttpServletRequest request,
                          HttpSession session){
        User user = userService.login(userCode, userPassword);
        if (user == null){
            //提示错误信息 并转发到登录页面失败:
            request.setAttribute("error","用户名或者密码有误!!!");
            return "login";
        }else{
            //成功了 将用户信息存入session 然后跳转成功页面
            session.setAttribute(Constants.USER_SESSION,user);
            return "redirect:/main.html";
        }
    }


    @RequestMapping("/main.html")
    public String main(HttpSession session){
        //对用户session进行判断
        if (session.getAttribute(Constants.USER_SESSION) == null){
            //未登录
            return "redirect:/login.html";
        }
        return "frame";
    }

    /**
     * 退出系统
     * @param session
     * @return
     */
    @RequestMapping("/logout.html")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "redirect:/login.html";
    }



    @RequestMapping("/exLogin.html")
    public String exLogin(@RequestParam String userCode,
                          @RequestParam String userPassword,
                          HttpServletRequest request,
                          HttpSession session){
        User user = userService.login(userCode, userPassword);
        if (user == null){
            throw new RuntimeException("用户名或者密码有误!!!!!");
        }else{
            //成功了 将用户信息存入session 然后跳转成功页面
            session.setAttribute(Constants.USER_SESSION,user);
            return "redirect:/main.html";
        }
    }

    //局部异常
//    @ExceptionHandler
//    public String exceptionHandler(Exception e,HttpServletRequest request){
//        request.setAttribute("e",e);
//        return "error";
//    }



    @Autowired
    private RoleService roleService;
    /**
     * 查询所有用户信息
     * @return
     */
    @RequestMapping("/userList.html")
    public String getUserList(Model model,
                              @RequestParam(value = "queryUserName",required = false)String queryUserName,
                              @RequestParam(value = "pageIndex",required = false)String pageIndex,
                              @RequestParam(value = "queryUserRole",required = false)String temp
            ){
        //查询用户列表
//        String queryUserName = request.getParameter("queryUserName");
//        String temp = request.getParameter("queryUserRole");
//        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
//        UserService userService = new UserServiceImpl();
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        /**
         * http://localhost:8090/SMBMS/userlist.do
         * ----queryUserName --NULL
         * http://localhost:8090/SMBMS/userlist.do?queryname=
         * --queryUserName ---""
         */
        System.out.println("queryUserName servlet--------"+queryUserName);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);
        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);
        }

        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                return "redirect:/syserror.html";
            }
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryUserName,queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }


        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
        List<Role> roleList =  roleService.getRoleList();
        model.addAttribute("userList", userList);
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "userlist";
    }

    @RequestMapping("/syserror.html")
    public String syserror(){
        return "error";
    }

    /**
     * 添加请求
     * @return
     */
    @RequestMapping("/toAddUser")
    public String toAddUser(){
        return "useradd";
    }

    /**
     * 添加操作
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("/doAddUser")
    public String doAddUser(User user,HttpServletRequest request,
                            @RequestParam(value = "attachs",required = false) MultipartFile[] attachs,
                            HttpSession session){
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;//假设文件上传是成功的
        //构建文件上传的目录
        String path = session.getServletContext().getRealPath("uploadFiles");
        for (int i = 0; i < attachs.length; i++) {
            if (i == 0){
                errorInfo = "uploadFileError";
            }
            if (i == 1){
                errorInfo = "uploadWorkError";
            }
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()){
                //判断文件大小
                int fileSize = 500000;//不超过50kb
                if(attach.getSize() > fileSize){
                    request.setAttribute(errorInfo,"文件上传大小不超过50KB");
//                return "useradd";
                    flag = false;
                }
                //判断文件类型
                String originalFilename = attach.getOriginalFilename();
                if (originalFilename.endsWith("jpg") ||
                        originalFilename.endsWith("png") ||
                        originalFilename.endsWith("jpeg")){
                    //目标文件名
                    String fileName =
                            System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";
                    File destFile = new File(path,fileName);
                    if (!destFile.exists()){
                        destFile.mkdirs();
                    }
                    try {
                        attach.transferTo(destFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo,"文件上传失败!!");
//                    return "useradd";
                        flag = false;
                    }
                    if (i == 0){
                        idPicPath = fileName;
                    }
                    if (i == 1){
                        workPicPath = fileName;
                    }
                }else{
                    request.setAttribute(errorInfo,"文件类型必须是jpg或者png或者jpeg");
//                return "useradd";
                    flag = false;
                }

            }
        }

        if (flag){
            user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
            user.setCreationDate(new Date());
            user.setIdPicPath(idPicPath);
            user.setWorkPicPath(workPicPath);
            if (userService.add(user)) {
                return "redirect:/userList.html";
            }
        }
        return "useradd";
    }


    @RequestMapping(value = "/add.html",method = RequestMethod.GET)
    public String add(@ModelAttribute("user")User user){
        return "user/useradd";
    }

    @RequestMapping(value = "/add.html",method = RequestMethod.POST)
    public String add(@Valid User user, BindingResult result,HttpSession session){
        if (result.hasErrors()){
            logger.info("验证未通过!!!");
            return "user/useradd";
        }
        user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if (userService.add(user)) {
            return "redirect:/userList.html";
        }
        return "user/useradd";
    }

    @RequestMapping("/toUpdateUser.html")
    public String toUpdateUser(@RequestParam String id,Model model){
        User user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "usermodify";
    }

    @RequestMapping("/doUpdateUser.html")
    public String doUpdateUser(User user,HttpSession session){
        user.setModifyBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        if (userService.modify(user)) {
            return "redirect:/userList.html";
        }
        return "usermodify";
    }

//    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    @GetMapping("/view/{id}")
    public String view(@PathVariable String id,Model model){
        User user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "userview";
    }

    @RequestMapping("/ucexist.html")
    @ResponseBody
    public String userCodeIsExist(@RequestParam String userCode){
        System.out.println("================="+userCode);
       User user=userService.selectUserCodeExist(userCode);
       Map<String,Object> map = new HashMap<String, Object>();
        System.out.println("1.hang"+user);
       System.out.println(user);
       if (user!=null){//用户名密码不存在
           map.put("userCode","exist");
       }else
       {
           map.put("userCode","noexist");
       }
       return JSON.toJSONString(map);
  }

  @RequestMapping("/viewUser.html")
    @ResponseBody
    public String viewUser(@RequestParam String id){
        User user=userService.getUserById(id);
      return JSON.toJSONString(user);
  }

}
